package cn.wolfcode.service.impl;

import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.*;
import cn.wolfcode.mapper.OrderInfoMapper;
import cn.wolfcode.mapper.PayLogMapper;
import cn.wolfcode.mapper.RefundLogMapper;
import cn.wolfcode.mapper.SeckillProductMapper;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMQResult;
import cn.wolfcode.redis.SeckillRedisKey;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.service.ISeckillProductService;
import cn.wolfcode.util.IdGenerateUtil;
import cn.wolfcode.web.feign.AlipayFeignApi;
import cn.wolfcode.web.feign.IntergralFeignApi;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import com.alibaba.fastjson.JSON;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by wolfcode-lanxw
 */
@Service
@Slf4j
public class OrderInfoSeviceImpl implements IOrderInfoService {
    @Autowired
    private ISeckillProductService seckillProductService;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private PayLogMapper payLogMapper;
    @Autowired
    private RefundLogMapper refundLogMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private SeckillProductMapper seckillProductMapper;
    @Autowired
    private AlipayFeignApi alipayFeignApi;
    @Autowired
    private IntergralFeignApi intergralFeignApi;

    @Value("${pay.returnUrl}")
    private String returnUrl;
    @Value("${pay.notifyUrl}")
    private String notifyUrl;


    @Override
    @Transactional
    public String doSeckill(Long seckillId, int time, Long phone) {
        //1.减少真实库存
        int seckillStock = seckillProductService.decrStock(seckillId);
        if (seckillStock == 0) {
            throw new BusinessException(SeckillCodeMsg.SECKILL_STOCK_OVER);
        }
        //2.创建秒杀订单
        String orderNo = createOrder(seckillId, time, phone);
        //3.往reids中存放订单信息 识别有没有重复下单 seckillOrderSet:time  seckillId:phone
        redisTemplate.opsForSet().add(SeckillRedisKey.SECKILL_ORDER_SET.getRealKey(String.valueOf(time)), seckillId + ":" + phone);
        return orderNo;
    }

    @Override
    public void cancelOrder(OrderMQResult message) {
        OrderInfo orderInfo = orderInfoMapper.find(message.getOrderNo());
        if (orderInfo.getStatus().equals(OrderInfo.STATUS_ARREARAGE)) {
            //订单已经过了15分钟还没有支付 将订单支付状态 未支付 改为 超时取消
            int count = orderInfoMapper.updateCancelStatus(message.getOrderNo(), OrderInfo.STATUS_TIMEOUT);
            if (count == 0) {
                throw new BusinessException(SeckillCodeMsg.CANCEL_ORDER_ERROR);
            }
            //回补真实库存
            seckillProductMapper.incrStock(message.getSeckillId());
            //回补预库存
            seckillProductService.syncRedisStockCount(message.getSeckillId(), message.getTime());
            //修改本地标识
            rocketMQTemplate.syncSend(MQConstant.CANCEL_SECKILL_OVER_SIGE_TOPIC, message.getSeckillId());
            log.info("执行了超时取消订单的逻辑...");
        }
    }

    @Override
    public OrderInfo find(String orderNo) {
        //return orderInfoMapper.find(orderNo);
        Object objJson = redisTemplate.opsForHash().get(SeckillRedisKey.SECKILL_ORDER_HASH.getRealKey(""), orderNo);
        if (StringUtils.isBlank(String.valueOf(objJson))) {
            return null;
        }
        return JSON.parseObject(String.valueOf(objJson), OrderInfo.class);
    }

    @Override
    public String payOnline(String orderNo) {
        //查询订单
        OrderInfo orderInfo = orderInfoMapper.find(orderNo);
        PayVo payVo = new PayVo();
        payVo.setOutTradeNo(orderNo);
        payVo.setTotalAmount(String.valueOf(orderInfo.getSeckillPrice()));
        payVo.setBody(orderInfo.getProductName());
        payVo.setSubject(orderInfo.getProductName());
        payVo.setNotifyUrl(notifyUrl);
        payVo.setReturnUrl(returnUrl);
        Result<String> result = alipayFeignApi.payOnline(payVo);
        if (result != null && !result.hasError()) {
            return result.getData();
        }
        return null;
    }

    @Override
    @Transactional
    public void payIntergral(String orderNo) {
        OrderInfo orderInfo = find(orderNo);
        //插入流水记录
        PayLog payLog = new PayLog();
        payLog.setTradeNo(orderInfo.getOrderNo());
        payLog.setOutTradeNo(orderInfo.getOrderNo());
        payLog.setTotalAmount(String.valueOf(orderInfo.getIntergral()));
        payLog.setPayType(OrderInfo.PAYTYPE_INTERGRAL);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        payLog.setNotifyTime(sdf.format(new Date()));
        payLogMapper.insert(payLog);
        //远程调用积分服务减积分记录
        OperateIntergralVo operateIntergralVo = new OperateIntergralVo();
        operateIntergralVo.setPk(orderNo);
        operateIntergralVo.setUserId(orderInfo.getUserId());
        operateIntergralVo.setValue(orderInfo.getIntergral());
        operateIntergralVo.setInfo("very good");
        Result<String> result = intergralFeignApi.payIntergral(operateIntergralVo);
        //{code:50602,msg:"余额不足"}
        if (result == null) {
            //操作积分失败
            throw new BusinessException(SeckillCodeMsg.INTERGRAL_SERVER_ERROR);
        }
        if (result.hasError()) {
            //积分余额不足
            throw new BusinessException(SeckillCodeMsg.INTERGRAL_NOT_ENOUGH);
        }
        //修改订单状态
        orderInfoMapper.changePayStatus(orderNo, OrderInfo.STATUS_ACCOUNT_PAID, OrderInfo.PAYTYPE_INTERGRAL);
    }

    //异步回调逻辑
    @Override
    public void paySuccess(String orderNo) {
        //1.往流水表中插入一条记录
        PayLog payLog = new PayLog();
        OrderInfo orderInfo = find(orderNo);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        payLog.setNotifyTime(sdf.format(date));
        payLog.setTradeNo(orderNo);
        payLog.setOutTradeNo(orderNo);
        payLog.setPayType(OrderInfo.PAYTYPE_ONLINE);
        payLog.setTotalAmount(String.valueOf(orderInfo.getSeckillPrice()));
        payLogMapper.insert(payLog);
        //2.修改订单状态为已支付
        orderInfoMapper.changePayStatus(orderNo, OrderInfo.STATUS_ACCOUNT_PAID, OrderInfo.PAYTYPE_ONLINE);
    }

    @Transactional
    @Override
    public void refundOnline(OrderInfo orderInfo) {
        //插入流水记录
        RefundLog refundLog = new RefundLog();
        refundLog.setOutTradeNo(orderInfo.getOrderNo());
        refundLog.setRefundAmount(String.valueOf(orderInfo.getSeckillPrice()));
        refundLog.setRefundType(orderInfo.getPayType());
        refundLog.setRefundReason("garbage 不想要了");
        refundLog.setRefundTime(new Date());
        refundLogMapper.insert(refundLog);
        //远程调用支付服务进行退款操作
        RefundVo refundVo = new RefundVo();
        refundVo.setOutTradeNo(orderInfo.getOrderNo());
        refundVo.setRefundAmount(String.valueOf(orderInfo.getSeckillPrice()));
        refundVo.setRefundReason("garbage 不要了");
        //result data 如果退款成功返回true 退款失败返回一个false
        Result<Boolean> result = alipayFeignApi.refundOnline(refundVo);
        if (result != null && !result.hasError()) {
            if (!result.getData()) {
                throw new BusinessException(SeckillCodeMsg.REFUND_ERROR);
            }
        }
        //修改订单状态为退款状态
        orderInfoMapper.changeRefundStatus(orderInfo.getOrderNo(), OrderInfo.STATUS_REFUND);
        //回补真实库存
        seckillProductMapper.incrStock(orderInfo.getSeckillId());
        //回补预库存
        seckillProductService.syncRedisStockCount(orderInfo.getSeckillId(), orderInfo.getSeckillTime());
        //修改本地标识
        rocketMQTemplate.sendOneWay(MQConstant.CANCEL_SECKILL_OVER_SIGE_TOPIC, orderInfo.getSeckillId());
    }

    @Override
    @GlobalTransactional
    public void refundIntergarl(OrderInfo orderInfo) {
        //插入一条流水记录
        RefundLog refundLog = new RefundLog();
        refundLog.setRefundTime(new Date());
        refundLog.setRefundType(orderInfo.getPayType());
        refundLog.setRefundReason("不要了");
        refundLog.setRefundAmount(String.valueOf(orderInfo.getIntergral()));
        refundLog.setOutTradeNo(orderInfo.getOrderNo());
        refundLogMapper.insert(refundLog);
        //远程调用积分服务加积分
        OperateIntergralVo operateIntergralVo = new OperateIntergralVo();
        operateIntergralVo.setValue(orderInfo.getIntergral());
        operateIntergralVo.setUserId(orderInfo.getUserId());
        operateIntergralVo.setPk(orderInfo.getOrderNo());
        operateIntergralVo.setInfo("不要了");
        Result<String> result = intergralFeignApi.refundIntergral(operateIntergralVo);
        //int i = 1 / 0;
        if (result != null && !result.hasError()) {
            //修改订单状态
            orderInfoMapper.changeRefundStatus(orderInfo.getOrderNo(), OrderInfo.STATUS_REFUND);
            //回补真实库存
            seckillProductMapper.incrStock(orderInfo.getSeckillId());
            //回补预库存
            seckillProductService.syncRedisStockCount(orderInfo.getSeckillId(), orderInfo.getSeckillTime());
            //修改本地标识
            rocketMQTemplate.sendOneWay(MQConstant.CANCEL_SECKILL_OVER_SIGE_TOPIC, orderInfo.getSeckillId());
        }
    }

    private String createOrder(Long seckillId, int time, Long phone) {
        SeckillProductVo seckillProductVo = seckillProductService.find(time, seckillId);
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCreateDate(new Date());
        orderInfo.setDeliveryAddrId(1L);
        orderInfo.setProductId(seckillProductVo.getProductId());
        orderInfo.setProductName(seckillProductVo.getProductName());
        orderInfo.setProductImg(seckillProductVo.getProductImg());
        orderInfo.setProductCount(seckillProductVo.getStockCount());
        orderInfo.setProductPrice(seckillProductVo.getProductPrice());
        orderInfo.setSeckillPrice(seckillProductVo.getSeckillPrice());
        orderInfo.setIntergral(seckillProductVo.getIntergral());
        orderInfo.setSeckillDate(new Date());
        orderInfo.setSeckillTime(time);
        orderInfo.setUserId(phone);
        orderInfo.setSeckillId(seckillId);
        orderInfo.setOrderNo(IdGenerateUtil.get().nextId() + "");
        orderInfo.setPayType(-1);
        orderInfoMapper.insert(orderInfo);
        return orderInfo.getOrderNo();
    }
}
